﻿using UnityEngine;

namespace Gameplay
{
    public enum EnemyState 
    {
        Patrol,
        Chase,
        Attack,
    }

    public class AIController:CharacterController
    {
        [SerializeField]private Transform[] _patrolPositions;
        [SerializeField] private float _patrolDistance;
        [SerializeField] private float _attackDistance;
        [SerializeField] private float _attackInterval;
        private float _timer;

        private Transform playerTransform;

        private Character _owner;
        private Character _target;
        
        private int _patrolIndex;
        
        private void Start()
        {
            _owner=GetComponent<Character>();
            playerTransform = GameObject.FindObjectOfType<PlayerController>().transform;
            _target = playerTransform.GetComponent<Character>();
            _patrolIndex = 0;
            _timer = _attackInterval;
        }

        private void Update()
        {
            if (_owner.Dead) 
            {
                return;
            }

            if (AIController.DistanceWithTarget(transform.position, playerTransform.position) >= _patrolDistance||_target.Dead) 
            {
                if (_character.MoveToTarget(_patrolPositions[_patrolIndex].position)) 
                {
                    _patrolIndex++;
                    if (_patrolIndex > _patrolPositions.Length - 1) 
                    {
                        _patrolIndex = 0;
                    }
                }
            }
            else if(AIController.DistanceWithTarget(transform.position, playerTransform.position) > _attackDistance) 
            {
                _character.MoveToTarget(playerTransform.position);
            }
            else if (AIController.DistanceWithTarget(transform.position, playerTransform.position) <= _attackDistance&&!_target.Dead)
            {
                _character.Idle();
                _timer -= Time.deltaTime;
                if (_timer <= 0) 
                {

                    _character.SkillManager.UseSkill(1001);
                    _timer = _attackInterval;
                }
                
            }
            
        }

        private static float DistanceWithTarget(Vector3 currentPos,Vector3 targetPos) 
        {
            return Vector3.Distance(new Vector3(currentPos.x,0,currentPos.z),new Vector3(targetPos.x,0,targetPos.z));
        }
    }
}
